<template>
  <div class="canvas-wrap" @mousedown="start" @mouseup="end" @mousemove="erase">
    <canvas width="500" height="500" ref="canvasEl3" id="c3"></canvas>
    <canvas width="500" height="500" ref="canvasEl2" id="c2"></canvas>
    <canvas width="500" height="500" ref="canvasEl1" id="c1"></canvas>
  </div>
</template>
<script lang="ts" setup>
import { ref, Ref, onMounted } from 'vue'
const canvasEl1 = ref(null) as Ref<HTMLCanvasElement>
const canvasEl2 = ref(null) as Ref<HTMLCanvasElement>
const canvasEl3 = ref(null) as Ref<HTMLCanvasElement>
let ctx1: CanvasRenderingContext2D
let ctx2: CanvasRenderingContext2D
let ctx3: CanvasRenderingContext2D
const width = 500
const height = 500
onMounted(() => {
  ctx1 = canvasEl1.value.getContext('2d')
  ctx2 = canvasEl2.value.getContext('2d')
  ctx3 = canvasEl3.value.getContext('2d')
  ctx1.fillStyle = '#ccc'
  ctx1.fillRect(0, 0, width, height)
  ctx2.fillStyle = '#999'
  ctx2.fillRect(0, 0, width, height)
  ctx3.fillStyle = '#666'
  ctx3.fillRect(0, 0, width, height)
})
let status = ''
function start() {
  status = 'erasing'
}
function end() {
  status = ''
}
const radius = 20
function erase(evt: MouseEvent) {
  if (!status) {
    return
  }
  let x = evt.offsetX
  let y = evt.offsetY
  let rect = [x - radius, y - radius, 2 * radius, 2 * radius]
  // console.log(rect)
  // ctx1.fillStyle = 'rgba(0,0,0,1)'
  let pos = (y * width - x) * 4
  let data = ctx1.getImageData(0, 0, width, height)

  if (data.data[pos] == 0) {
    ctx2.clearRect(rect[0], rect[1], rect[2], rect[3])
  }
  ctx1.clearRect(rect[0], rect[1], rect[2], rect[3])
}
</script>
<style lang="less">
.canvas-wrap {
  width: 500px;
  height: 500px;
  position: relative;
  canvas {
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>
